package com.beiding.sqlbuilder.impl;

import com.beiding.sqlbuilder.BuilderContext;
import com.beiding.sqlbuilder.ConditionUnit;
import com.beiding.sqlbuilder.ConditionUnitContainer;
import com.beiding.sqlbuilder.ConditionUnitHolder;
import com.beiding.sqlbuilder.TableHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SimpleConditionUnitContainer implements ConditionUnitContainer {

    protected List<ConditionUnitHolder> conditionUnitHolders;

    protected List<ConditionUnit> conditionUnits;

    protected BuilderContext builderContext;

    protected boolean inner = true;

    public SimpleConditionUnitContainer() {
        this.conditionUnits = new ArrayList<>();
    }

    public SimpleConditionUnitContainer(ConditionUnit... conditionUnits) {
        this(Arrays.asList(conditionUnits));
    }


    public SimpleConditionUnitContainer(List<ConditionUnit> conditionUnits) {
        this.conditionUnits = conditionUnits;
    }

    public void setInner(boolean inner) {
        this.inner = inner;
    }

    public void addConditionUnit(ConditionUnit unit) {
        this.conditionUnits.add(unit);
    }

    @Override
    public boolean isInner() {
        return inner;
    }

    public void setBuilderContext(BuilderContext builderContext) {
        this.builderContext = builderContext;
    }

    @Override
    public List<ConditionUnitHolder> getConditionUnits() {
        return conditionUnitHolders;
    }

    @Override
    public void build(BuilderContext builderContext) { //构建时递归构建
        if (conditionUnitHolders == null) {
            if (conditionUnits.size() == 0) {
                throw new RuntimeException("条件容器中至少包含一个条件");
            }
            conditionUnitHolders = new ArrayList<>();
            for (ConditionUnit conditionUnit : this.conditionUnits) {
                conditionUnit.build(builderContext);
                conditionUnitHolders.add(ConditionUtils.buildConditionUnitHolder(conditionUnit, builderContext.getConditionUnitHandlers()));
            }
        }
    }

}
